package com.choosefine.it.team.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.dao.PriceAdjustLogMapper;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.StringUtils;
import com.choosefine.it.team.dao.AuthorizationPictureMapper;
import com.choosefine.it.team.dao.ItemInfoMapper;
import com.choosefine.it.team.model.AuthorizationPicture;
import com.choosefine.it.team.model.ItemInfo;
import com.choosefine.it.team.model.PriceAdjustLog;
import com.choosefine.it.team.model.dto.TeamDTO;
import com.choosefine.it.team.model.po.TeamInfoParamesAdd;
import com.choosefine.it.team.model.po.TeamInfoParamesUpdate;
import com.choosefine.it.team.model.vo.ItemInfoVO;
import com.choosefine.it.team.model.vo.ProjectInfoFindTeamVO;
import com.choosefine.it.team.model.vo.TeamMoneyMgtVO;
import com.choosefine.it.team.model.vo.TeamVO;
import com.choosefine.it.team.model.vo.TeamWorkerMoneyMgtVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service("itemInfoService")
public class ItemInfoService {

	@Autowired
	private ItemInfoMapper itemInfoMapper;
	@Autowired
	private PriceAdjustLogMapper priceAdjustLogMapper;
	
	@Autowired
	private AuthorizationPictureMapper authorizationPictureMapper;
	
	/**
	 * 11.25 dzq 根据用户code 查询该用户的班组信息
	 * 
	 * @param userCode
	 *            用户code
	 * @param pageDTO
	 * @return
	 */
	public Page<ItemInfo> selectByuserCode(String userCode, PageDTO pageDTO) {
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<ItemInfo> list = itemInfoMapper.selectByUserCode(userCode);
		return list;
	}

	/**
	 * 12.10查找某项目下的班组数量dzq
	 * 
	 * @return
	 */
	public int selectCountTeamByProject(Map<String, Object> map) {
		return itemInfoMapper.selectCountTeamByProject(map);
	}
	
	public Page<ItemInfo> getTeamListByProject(Map<String, Object> map, PageDTO pageDTO) {
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<ItemInfo> list = itemInfoMapper.getTeamListByProject(map);
		return list;
	}
	


	public ItemInfo getTeamInfoById(Integer id) {
		return itemInfoMapper.getTeamInfoById(id);
	}


	/**
	 * @author chenjian
	 * @time 2016-12-16 下午4:37:56
	 */
	public int saveTeam(ItemInfo itemInfo) {
		return itemInfoMapper.saveTeam(itemInfo);
	}

	/**
	 * 新增班组相关信息
	 * @author chenjian
	 * @time 2016-12-14 下午5:24:34
	 */
	@Transactional
	public int saveTeam(TeamInfoParamesAdd teamInfoParamesAdd) {
		//新增班组信息
		ItemInfo itemInfo = saveItemInfo(teamInfoParamesAdd);
		
		//新增班组与班组类型表
//		List<TeamAndTeamTypeRelation> teamAndTeamTypeRelationList = teamAndTeamTypeRelationList(teamInfoParamesAdd.getTeamTypeIdes(),itemInfo.getId());
//		if(teamAndTeamTypeRelationList.size()>0){
//			teamAndTeamTypeRelationMapper.saveTeamAndTeamTypeRelation(teamAndTeamTypeRelationList);
//		}
		
		//保存项目承包人授权书信息
		List<AuthorizationPicture> authorizationPictureList = authorizationPictureList(teamInfoParamesAdd.getTeamAuthorization(),itemInfo.getId());
		if(authorizationPictureList.size()>0){
			authorizationPictureMapper.saveAuthorizationPictureList(authorizationPictureList);
		}
		
		// TODO 推送给班组承包人  承包人和项目已建立关系 传递项目编号projectCode可以查看详情 [您已加入"下沙建筑公司--龙湖滟澜山" 项目,点击查看详情....] 
		return itemInfo.getId();
	}
	
	/**
	 * @Description：新增班组信息
	 * @Author：chenjian
	 * @Create Date：2017年2月25日
	 * @param：
	 * @return：
	 */
	private ItemInfo saveItemInfo(TeamInfoParamesAdd teamInfoParamesAdd){ 
		ItemInfo itemInfo = new ItemInfo();
		itemInfo.setUserName(teamInfoParamesAdd.getUserName());
		itemInfo.setUserCode(teamInfoParamesAdd.getUserCode());
		itemInfo.setProjectCode(teamInfoParamesAdd.getProjectCode());
		itemInfo.setAffiliatedUnitsId(teamInfoParamesAdd.getAffiliatedUnitsId());
		itemInfo.setProjectTypeId(teamInfoParamesAdd.getProjectTypeId());
		itemInfo.setIsValid(CommonConstant.VALID);
		itemInfo.setCtime(DateUtils.getNowTime());
		itemInfo.setProjectStage(teamInfoParamesAdd.getProjectStage());
		itemInfo.setTotalPrice(teamInfoParamesAdd.getTotalPrice());
		itemInfo.setTeamName(teamInfoParamesAdd.getTeamName());
		itemInfo.setAffiliatedUnitsCode(teamInfoParamesAdd.getAffiliatedUnitsCode());
		// 新增班组
		itemInfoMapper.saveTeam(itemInfo);
		return itemInfo;
	}
	
//	/**
//	 * 班组与班组类型集合
//	 * @author chenjian
//	 * @time 2016年12月30日下午2:36:56
//	 */
//	private List<TeamAndTeamTypeRelation> teamAndTeamTypeRelationList(String teamTypeIdes,int teamId){
//		List<TeamAndTeamTypeRelation> teamAndTeamTypeRelationList = new ArrayList<>();
//		if(teamTypeIdes!=null&&!"".equals(teamTypeIdes)){
//			String []teamTypes = teamTypeIdes.split(",");
//			for(int i=0;i<teamTypes.length;i++){
//				TeamAndTeamTypeRelation teamAndTeamTypeRelation = new TeamAndTeamTypeRelation();
//				teamAndTeamTypeRelation.setTeamId(teamId);
//				teamAndTeamTypeRelation.setTeamTypeId(Integer.parseInt(teamTypes[i]));
//				teamAndTeamTypeRelationList.add(teamAndTeamTypeRelation);
//			}
//		}
//		return teamAndTeamTypeRelationList;
//	}
	
	/**
	 * 班组授权书集合
	 * @author chenjian
	 * @time 2016年12月30日下午2:44:03
	 */
	private List<AuthorizationPicture> authorizationPictureList(String teamAuthorization,int teamId){
		List<AuthorizationPicture> authorizationPictureList = new ArrayList<>();
		if(teamAuthorization!=null&&!"".equals(teamAuthorization)){
			String[] pictureList = teamAuthorization.split(",");
			for(int i=0;i<pictureList.length;i++){
				AuthorizationPicture authorizationPicture = new AuthorizationPicture();
				authorizationPicture.setOriginalPicture(pictureList[i]);
				authorizationPicture.setType(3);
				authorizationPicture.setCtime(DateUtils.getNowTime());
				authorizationPicture.setIsValid(CommonConstant.VALID);
				authorizationPicture.setItemId(teamId);
				authorizationPicture.setItemType(2);
				authorizationPictureList.add(authorizationPicture);
			}
		}
		return authorizationPictureList;
	}

	/**
	 * 修改班组相关信息
	 * 
	 * @author chenjian
	 * @time 2016-12-14 下午5:24:53
	 */
	@Transactional
	public int updateTeam(TeamInfoParamesUpdate teamInfoParamesUpdate) {
		// 修改班组
		int result = updateTeamInfo(teamInfoParamesUpdate);

		//保存班组分包总价的更改记录
		if(teamInfoParamesUpdate.getAdjustedSubPrice() !=null && !"".equals(teamInfoParamesUpdate.getAdjustedSubPrice())){
			saveItemPriceRecord(teamInfoParamesUpdate);
			
		}
		
//		//删除班组与班组类型表数据
//		teamAndTeamTypeRelationMapper.deleteByTeamId(itemInfo.getId());
//		//新增班组与班组类型表
//		List<TeamAndTeamTypeRelation> teamAndTeamTypeRelationList = teamAndTeamTypeRelationList(teamInfoParamesUpdate.getTeamTypeIdes(),itemInfo.getId());
//		if(teamAndTeamTypeRelationList.size()>0){
//			teamAndTeamTypeRelationMapper.saveTeamAndTeamTypeRelation(teamAndTeamTypeRelationList);
//		}
		
		//删除项目承包人授权书信息
		authorizationPictureMapper.deleteByTeamId(teamInfoParamesUpdate.getTeamId());
		//保存项目承包人授权书信息
		List<AuthorizationPicture> authorizationPictureList = authorizationPictureList(teamInfoParamesUpdate.getTeamAuthorization(),teamInfoParamesUpdate.getTeamId());
		if(authorizationPictureList.size()>0){
			authorizationPictureMapper.saveAuthorizationPictureList(authorizationPictureList);
		}
		// TODO 如果班组承包人发生变化 oldTeamInfo.userCode != teamInfoParamesUpdate.userCode
		// if(!teamInfoParamesUpdate.userCode.equals(oldTeamInfo.userCode)){
		//		TODO 推送给旧班组承包人  承包人和项目已删除关系 传递项目编号projectCode可以查看详情 [您已离开"下沙建筑公司--龙湖滟澜山" 项目,点击查看详情....] 
		//		TODO 推送给新班组承包人  承包人和项目已建立关系 传递项目编号projectCode可以查看详情 [您已加入"下沙建筑公司--龙湖滟澜山" 项目,点击查看详情....] 
		// }
		return result;
	}
	
	/**
	 * 
	 * @Description：修改班组信息
	 * @Author：chenjian
	 * @Create Date：2017年2月25日
	 * @param：
	 * @return：
	 */
	private int updateTeamInfo(TeamInfoParamesUpdate teamInfoParamesUpdate){
		ItemInfo itemInfo = new ItemInfo();
		itemInfo.setUserName(teamInfoParamesUpdate.getUserName());
		itemInfo.setUserCode(teamInfoParamesUpdate.getUserCode());
		itemInfo.setProjectCode(teamInfoParamesUpdate.getProjectCode());
		itemInfo.setAffiliatedUnitsId(teamInfoParamesUpdate.getAffiliatedUnitsId());
		itemInfo.setProjectTypeId(teamInfoParamesUpdate.getProjectTypeId());
		itemInfo.setProjectStage(teamInfoParamesUpdate.getProjectStage());
		itemInfo.setId(teamInfoParamesUpdate.getTeamId());
		itemInfo.setTotalPrice(teamInfoParamesUpdate.getTotalPrice());
		itemInfo.setAdjustedSubPrice(teamInfoParamesUpdate.getAdjustedSubPrice());
		itemInfo.setAdjustedReason(teamInfoParamesUpdate.getAdjustedReason());
		itemInfo.setTeamName(teamInfoParamesUpdate.getTeamName());
		itemInfo.setAffiliatedUnitsCode(teamInfoParamesUpdate.getAffiliatedUnitsCode());
		// 修改班组
		itemInfoMapper.updateTeam(itemInfo);
		return itemInfo.getId();
	}
	
	//保存班组分包总价的更改记录
	private void saveItemPriceRecord(TeamInfoParamesUpdate teamInfoParamesUpdate){
		PriceAdjustLog priceAdjustLog = new PriceAdjustLog(
				teamInfoParamesUpdate.getTeamId(),
				teamInfoParamesUpdate.getAdjustedSubPrice(), 
				teamInfoParamesUpdate.getAdjustedReason(), 2,//1表示项目，2表示班组
				teamInfoParamesUpdate.getOperatorCode());
		priceAdjustLogMapper.savePriceAdjustRecord(priceAdjustLog);
		priceAdjustLog = null;
	}

	/**
	 * @author chenjian
	 * @time 2016-12-16 下午4:37:48
	 */
	public int deleteTeam(Map<String, Object> map) {
		return itemInfoMapper.deleteTeam(map);
	}


	public ItemInfoVO teamDetail(Integer teamId) {
		return itemInfoMapper.teamDetail(teamId);
	}

	/**
	 * 根据userCode查询该用户所挂靠的公司
	 * @param userCode
	 * @return
	 */
	public List<String> selectTeamAffiliatedUnitsByUserCode(String userCode){
		return itemInfoMapper.selectTeamAffiliatedUnitsByUserCode(userCode);
	}

	public Page<TeamMoneyMgtVO> selectTeamWorkerSalarySum(Map<String, Object>map,PageDTO pageDTO){
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return itemInfoMapper.selectTeamWorkerSalarySum(map);
	}
	public Page<TeamWorkerMoneyMgtVO> selectTeamWorkerSalaryBy(Map<String, Object>map,PageDTO pageDTO){
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return itemInfoMapper.selectTeamWorkerSalaryBy(map);
	}

	public Integer getWorkerNumByTeamId(Integer teamId) {

		return itemInfoMapper.getWorkerNumByTeamId(teamId);
	}

	public List<ItemInfo> findTeamByCode(Map<String, Object> params) {
		return itemInfoMapper.findTeamByCode(params);
	}

	
	public List<ItemInfo> findTeamesByProjectCode(Map<String, Object> map){
		return itemInfoMapper.findTeamesByProjectCode(map);
	}
	
	/**
	 * @Description：条件查询项目班组
	 * @Author：chenjian
	 * @Create Date：2017年2月15日
	 * @param：
	 * @return：
	 */
	public Page<TeamVO> queryTeamList(TeamDTO teamDTO) {
		PageHelper.startPage(teamDTO.getPageNum(), teamDTO.getPageSize());
		Map<String, Object> map = new HashMap<>();
		if(StringUtils.isNotBlank(teamDTO.getCompanyName())){
			map.put("companyName", teamDTO.getCompanyName().trim());
		}
		if(StringUtils.isNotBlank(teamDTO.getName())){
			map.put("name", teamDTO.getName().trim());
		}
		if(StringUtils.isNotBlank(teamDTO.getProjectCode())){
			map.put("projectCode", teamDTO.getProjectCode().trim());
		}
		if(StringUtils.isNotBlank(teamDTO.getTeamName())){
			map.put("teamName", teamDTO.getTeamName());
		}
		if(teamDTO.getProjectTypeId()!=null&&teamDTO.getProjectTypeId()!=0){
			map.put("projectTypeId", teamDTO.getProjectTypeId());
		}
		map.put("isValid", teamDTO.getIsValid());
		Page<TeamVO> page = itemInfoMapper.queryTeamList(map);
		return page;
	}

	/**
	 * @Description：校验同一项目同一分包承包人班组名不能重复(陈健)
	 * @Author：chenjian
	 * @Create Date：2017年2月25日
	 * @param：
	 * @return：
	 */
	public Integer checkTeamName(Map<String, Object> map) {
		return itemInfoMapper.checkTeamName(map);
	}
}
